import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:seedfour/app/models/file_search_list_entity.dart';

import '../../services/api_service.dart';
import '../../services/common_service.dart';

class FileSearchLogic extends GetxController {
  final apiService = Get.find<ApiService>();
  final commonService = Get.find<CommonService>();

  final loadingTip = '加载中...';
  final noMoreTip = '没有更多了';

  var isLoading = false.obs;
  var bottomTips = ''.obs;
  var files = <FileSearchData>[].obs;

  final scrollController = ScrollController();
  final caseNameText = TextEditingController();
  final userNameText = TextEditingController();
  final keywordText = TextEditingController();

  var caseName = '';
  var userName = '';
  var keyword = '';
  var fileType = Rxn<int>();

  final pageSize = 20;
  int _page = 1;

  @override
  void onInit() {
    super.onInit();
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        _searchResult();
      }
    });
  }

  void onSearch() {
    if (caseNameText.text.isEmpty &&
        userNameText.text.isEmpty &&
        keywordText.text.isEmpty) {
      Get.snackbar('提示', '请至少输入一个条件进行检索');
      return;
    }

    _page = 1;
    files.clear();
    isLoading.value = true;
    caseName = caseNameText.text;
    userName = userNameText.text;
    keyword = keywordText.text;
    _searchResult();
  }

  void selectFileType(int type) {
    fileType.value = type;
  }

  void _searchResult() {
    apiService
        .searchFiles(
          _page,
          pageSize,
          commonService.getRole(),
          caseName: caseName,
          name: userName,
          fileType: fileType.value,
          keyword: keyword,
        )
        .then((result) => {
              isLoading.value = false,
              _page++,
              if (result != null)
                {
                  files.addAll(result.data ?? []),
                  if (result.data!.length < pageSize)
                    {bottomTips.value = noMoreTip}
                  else
                    {bottomTips.value = loadingTip}
                }
              else
                {bottomTips.value = noMoreTip}
            });
  }

  @override
  void onClose() {
    caseNameText.dispose();
    userNameText.dispose();
    scrollController.dispose();
    super.onClose();
  }
}
